package com.fr.transfer.cal;

import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.data.impl.NameDatabaseConnection;
import com.fr.data.impl.sap.SAPTransfer;
import com.fr.report.core.cal.BEBSingleRowJob;

import java.sql.Connection;
import java.util.Map;

public class SAPTransferSingleRowJob implements BEBSingleRowJob {
	private SAPTransfer transfer;
	private SubmitJober jober;
	private Connection conn = null;
	private Dialect dialect;
	private Map connectionMap;
	
	public SAPTransferSingleRowJob(SAPTransfer transfer, Map connectionMap) {
		this.transfer = transfer;
		if (transfer.getSubmitType() == SAPTransfer.SUBMIT_TYPE_INSERT) {
			jober = new InsertJober(transfer.getExportTable(), transfer.getColumnConfigs());
		} else if (transfer.getSubmitType() == SAPTransfer.SUBMIT_TYPE_DELETE) {
			jober = new DeleteJober(transfer.getExportTable(), transfer.getColumnConfigs());
		} else if (transfer.getSubmitType() == SAPTransfer.SUBMIT_TYPE_INTELLI) {
			jober = new IntelliJober(transfer.getExportTable(), transfer.getColumnConfigs());
		} else if (transfer.getSubmitType() == SAPTransfer.SUBMIT_TYPE_UPDATE) {
			jober = new UpdateJober(transfer.getExportTable(), transfer.getColumnConfigs());
		}
		this.connectionMap = connectionMap;
	}

	public void doJob(Object[] objs) throws Exception {
		if (objs.length == transfer.getColumnConfigCount()) {
			if (conn == null) {
				conn = (Connection)connectionMap.get(transfer.getExportDataBaseName());
				if (conn == null) {
					NameDatabaseConnection db = new NameDatabaseConnection(transfer.getExportDataBaseName());
					conn = db.createConnection();
					conn.setAutoCommit(false);
					connectionMap.put(transfer.getExportDataBaseName(), conn);
				}
				dialect = DialectFactory.generateDialect(conn);
			}
			
			jober.dealSubmit(dialect, conn, objs);
		} else {
			throw new RuntimeException("SAPTransfer Error: ColSize not compatiable!");
		}
	}
}
